import { keys, findIndex, random } from 'lodash'
import { getCurrentInstance, inject, onMounted, onUnmounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export const transform_pre_fn = {
  'fn.number': (x) => {
    if (x) {
      return Number(x)
    } else {
      return null
    }
  },
  'fn.number0': (x, _default) => {
    if (x) {
      return Number(x)
    } else {
      if (x == 0) {
        return 0
      }
      if (_default != undefined && _default.toString().length > 0) {
        // return _default
      }
      return null
    }
  },
  'fn.string': (x, _default) => {
    if (x) {
      return String(x)
    } else {
      if (_default != undefined && _default.toString().length > 0) {
        // return _default
      }
      return null
    }
  },
  'fn.array': (x, _default) => {
    if (x) {
      return x
    } else {
      if (_default != undefined && _default.toString().length > 0) {
        // return _default
      }
      return null
    }
  },
  'fn.pageSize': (x, proxy_pagination) => {
    if (x) {
      return Number(x)
    } else {
      return proxy_pagination.pageSize || 10
    }
  },
  'fn.pageCurrent': (x) => {
    if (x) {
      return Number(x)
    } else {
      return 1
    }
  },
}

export const useUrl = ({
  fn,
  formState = [],
  pagination = [
    {
      to: 'size', //表单中的名称
      from: 'pageSize', //地址栏中的名称
      fn: transform_pre_fn['fn.pageSize'],
    },
    {
      to: 'index',
      from: 'current',
      fn: transform_pre_fn['fn.pageCurrent'],
    },
  ],
}) => {
  let { proxy } = getCurrentInstance()
  let route = useRoute()
  let watch_list = []
  let router = useRouter()
  let path = route.path

  //从地址栏中映射到form_state
  const fromQueryToState = () => {
    let _query = route.query
    let _pagin = {}
    let _form = {}

    pagination.map((x) => {
      _pagin[x.from] = x.fn
        .bind(null, _query[x.to], proxy.pagination?.data)
        .call()
    })
    //状态表单的转换
    formState.map((x) => {
      _form[x.key] = x.fn.bind(null, _query[x.key], x.default).call()

      // console.log(x)
      //   if (x.key && !_form[x.key]) {
      //  console.log(_form[x.key].default)
      //   }
    })

    for (var prop in _pagin) {
      proxy.pagination.data[prop] = _pagin[prop]
    }
    for (prop in _form) {
      // console.log(formState, prop)
      //proxy.form_state.data.startTime = '2012-12-12'

      //如果有默认值，需要在空的时候传入到state中
      let _index = findIndex(formState, { key: prop })
      proxy.form_state.data[prop] =
        _form[prop] != undefined ? _form[prop] : formState[_index].default

      // if (formState[_index].default != undefined) {
      //   if (!proxy.form_state.data[prop]) {
      //     proxy.form_state.data[prop] = formState[_index].default
      //   } else {
      //     proxy.form_state.data[prop] = _form[prop] || formState[_index].default
      //   }
      // } else {
      //   proxy.form_state.data[prop] = _form[prop]
      // }
    }
  }

  //从form_state映射到地址栏中
  const fromStateToQuery = (_info) => {
    let _query = {}
    //页码的转换
    pagination.map((x) => {
      if (proxy.pagination?.data) {
        _query[x.to] = x.fn.bind(null, proxy.pagination.data[x.from]).call()
      }
    })
    //状态表单的转换
    formState.map((x) => {
      _query[x.key] = x.fn
        .bind(null, proxy.form_state.data[x.key], x.default)
        .call()

      let _index = findIndex(formState, { key: x.key })

      if (!_query[x.key] && formState[_index].default != undefined) {
        _query[x.key] = formState[_index].default
      }
    })

    //把state中空值过滤掉
    for (var prop in _query) {
      if (!_query[prop] && _query[prop] != 0) {
        delete _query[prop]
      }
      // console.log(_query[prop])
      // if (_query[prop] instanceof Array) {
      //   _query[prop] = '[' + _query[prop].join(',') + ']'
      // }
    }
    // if (proxy.canWatchQuery != undefined && proxy.canWatchQuery == false) {
    //   return
    // }
    router.push({
      query: _query,
      //  path: path,
      ..._info,
    })
  }

  onMounted(() => {
    //监视router.query
    let watchFn = () => {
      let _watch = watch(
        () => route.query,
        async () => {
          //canWatchQuery表明是监听起作用
          fromQueryToState()
          // fromStateToQuery({ path: route.path })
          //console.log(proxy.canWatchQuery)
          if (
            proxy.canWatchQuery != undefined &&
            proxy.canWatchQuery == false
          ) {
            return
          }
          // console.log(route.path, path)
          //跳转时 中断请求
          if (route.path != path) {
            return
          }

          let _result = await fn()
          //地址栏中是否有需要滚动到位置的参数,如果有执行滚动操作,否则
          if (route.query.touch_pos) {
            window.scrollTo(0, Number(route.query.touch_pos))
          }
        },
        {
          deep: true,
          immediate: true,
        }
      )
      watch_list.push(_watch)
    }
    watchFn()
  })
  //跳转页面，并附加参数到history记录中
  const toLink = async (_obj) => {
    watch_list.map((_w) => {
      _w()
    })

    //记录这个参数
    router.push({
      path: route.path,
      query: { ...route.query, touch_pos: window.pageYOffset },
    })

    setTimeout(async () => {
      let _result = await router.push(_obj)
    })
  }
  //强制刷新
  let forceFresh = () => {
    router.push({
      path: route.path,
      query: { ...route.query, rand: random(100000000) },
    })
  }

  //清除watch
  onUnmounted(() => {
    watch_list.map((_w) => {
      _w()
    })
  })

  return { fromStateToQuery, fromQueryToState, toLink, forceFresh }
}
